package com.plug.controller;

import com.plug.common.consts.Code;
import com.plug.common.model.ExceptionResult;
import com.plug.common.model.JsonResult;
import com.plug.controller.util.AbstractController;
import com.plug.entity.PlugCompareTask;
import com.plug.entity.PlugContrast;
import com.plug.entity.PlugDatasource;
import com.plug.service.IPlugCompareTaskService;
import com.plug.service.IPlugContrastService;
import com.plug.service.IPlugDatasourceService;
import com.plug.service.IPlugRecordService;
import com.plug.util.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * Created by slayes on 2017/1/12.
 */
@Controller
@RequestMapping("/taskCompare")
public class TaskCompareController extends AbstractController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private IPlugCompareTaskService plugCompareTaskService;

    @Autowired
    private IPlugContrastService plugContrastService;

    @Autowired
    private IPlugRecordService plugRecordService;

    @Autowired
    private IPlugDatasourceService plugDatasourceService;

    /**
     * 新增对比任务
     * @param plugCompareTask
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<Object> save(PlugCompareTask plugCompareTask){
        try{
            plugCompareTask.setCreatetime(new Date());

            if(StringUtils.isNull(plugCompareTask.getPlugContrastId()))
                throw new Exception("任务配置信息不能为空！");

            if(StringUtils.isNull(plugCompareTask.getCompareFileds()))
                throw new Exception("对比列名不能为空！");

            if(StringUtils.isNull(plugCompareTask.getCompareTimeQuantum()))
                throw new Exception("对比时间间隔不能为空！");

            int result = plugCompareTaskService.save(plugCompareTask);

            JsonResult jsonResult = new JsonResult();
            if(result > 0){
                jsonResult.setCode(Code.SUCCESS);
                jsonResult.setMessage("保存成功！");
            }else {
                jsonResult.setCode(Code.FAILED);
                jsonResult.setMessage("保存失败！");
            }

            return new ResponseEntity<Object>(jsonResult, HttpStatus.OK);
        }catch (Exception e){
            return new ResponseEntity<Object>(new ExceptionResult(e), HttpStatus.NOT_IMPLEMENTED);
        }
    }

    /**
     * 删除对比任务
     * @param arr
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<Object> delete(String arr){
        System.out.println(11);
        logger.debug("------------------idArray:{}-----------------", arr);
        try{
            List<Integer> list = new ArrayList<>();
            String[] jsonArray = arr.split(",");
            for (int i = 0; i < jsonArray.length; i++) {
                list.add(Integer.valueOf(jsonArray[i]));
            }

            int result = plugCompareTaskService.deleteBatch(list);

            JsonResult jsonResult = new JsonResult();
            if(result > 0){
                jsonResult.setCode(Code.SUCCESS);
                jsonResult.setMessage("删除成功！");
            }else {
                jsonResult.setCode(Code.FAILED);
                jsonResult.setMessage("删除失败！");
            }

            return new ResponseEntity<Object>(jsonResult, HttpStatus.OK);
        } catch (Exception e){
            return new ResponseEntity<Object>(new ExceptionResult(e), HttpStatus.NOT_IMPLEMENTED);
        }
    }

    /**
     * 分页查询
     * @param offset
     * @param limit
     * @return
     */
    @RequestMapping(value = "/findPages", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<Object> findPages(@RequestParam("offset")Integer offset,@RequestParam("limit")Integer limit){
        try{
            limit = limit == null ? 25 : limit;

            int total = plugCompareTaskService.findTotal();

            List<Map<String,Object>> resultList = plugCompareTaskService.findPages((offset - 1) * limit, limit);

            JsonResult jsonResult = new JsonResult();
            if(resultList != null && resultList.size() > 0){
                jsonResult.setCode(Code.SUCCESS);
            }
            jsonResult.putData("data", resultList);
            jsonResult.putData("offset", offset);
            jsonResult.putData("total", total);

            return new ResponseEntity<Object>(jsonResult, HttpStatus.OK);
        } catch (Exception e){
            return new ResponseEntity<Object>(new ExceptionResult(e), HttpStatus.NOT_IMPLEMENTED);
        }
    }

    /**
     * 查询所有任务配置
     * @return
     */
    @RequestMapping(value = "/getContrast", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<Object> getContrast(){
        try {
            List<Map<String, Object>> plugContrastList = plugContrastService.findDataSourceAndContrast();

            List<Map<String, Object>> listMap = new ArrayList<>();
            for(Map<String, Object> key : plugContrastList){
                Map<String, Object> map = new HashMap<>();
                map.put("value", key.get("id"));
                map.put("text", key.get("sds_name")+","+key.get("src_tab")+","+key.get("tds_name")+","+key.get("tgt_tab"));
                listMap.add(map);
            }

            JsonResult jsonResult = new JsonResult();
            if(listMap != null && listMap.size() > 0)
                jsonResult.setCode(Code.SUCCESS);

            jsonResult.putData("data", listMap);

            return new ResponseEntity<Object>(jsonResult, HttpStatus.OK);
        } catch (Exception e){
            return new ResponseEntity<Object>(new ExceptionResult(e), HttpStatus.OK);
        }
    }

    /**
     * 根据配置任务信息获取表名
     * @param id
     * @return
     */
    @RequestMapping(value = "/getColumn", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<Object> getColumn(@RequestParam("id")Long id){
        try {

            PlugContrast plugContrast = plugContrastService.findByID(id);
            PlugDatasource plugDatasource = plugDatasourceService.findByID(plugContrast.getTgtDsId());

            List<String> columnList = plugRecordService.findTableColumn(plugDatasource, plugContrast.getTgtTab());

            List<Map<String, Object>> listMap = new ArrayList<>();

            for (String column : columnList){
                Map<String, Object> map = new HashMap<>();
                map.put("text", column);
                map.put("value", column);
                listMap.add(map);
            }

            JsonResult jsonResult = new JsonResult();

            if(listMap != null && listMap.size() > 0)
                jsonResult.setCode(Code.SUCCESS);
            jsonResult.putData("data", listMap);

            return new ResponseEntity<Object>(jsonResult, HttpStatus.OK);
        } catch (Exception e){
            return new ResponseEntity<Object>(new ExceptionResult(e), HttpStatus.OK);
        }
    }
}
